local function cmd2str(cmd)
	local f = io.popen(cmd)
	local str = f:read("*a")
	assert(io.close(f))
	return str
end

local function get_modules(str)
	local tb = {}
	local i = 1
	while true do
		local j = string.find(str, "\n", i)
		if not j then
			break
		end
		tb[#tb + 1] = string.sub(str, i, j - 1)
		i = j + 1
	end
	return tb
end

local function is_file_exist(filename)
	local f = io.open(filename, "rb")
	if not f then
		return
	end
	assert(io.close(f))
	return true
end

local envs = {}
function require(str)
	if envs[str] then
		return envs[str]
	end
	envs[str] = {require = require}
	envs[str]._ENV = envs[str]
	local filename = str 
	if not is_file_exist(str) then
		local pos = string.find(str, ".", 1, true)
		filename = "script/module/" .. string.sub(str, 1, pos - 1) .. "/" .. string.sub(str, pos + 1) .. ".lua"
	end
	local fun, err = loadfile(filename, nil, envs[str])
	if fun then
		fun()
		return envs[str]
	elseif not string.find(err, "No such file or directory") then
		assert(nil, err)
	end
end

local set = {}
for _, v in ipairs(get_modules(cmd2str(os.getenv("OS") == "Windows_NT" and "dir/b script\\module" or "ls script/module"))) do
	local proto = require(v .. ".Proto")
	if proto then
		for k, v in pairs(proto) do
			local sub = string.sub(k, 1, 2)
			if sub == "CG" or sub == "GC" then
				if set[k] then
					assert()
				end
				set[k] = v
			end
		end
	end
end
local proto_id = {}
for k, v in pairs(require("script/common/ProtoID.lua")) do
	if type(v) == "string" then
		proto_id[v] = k
		set_proto_id(v, k)
	end
end
for _, v in ipairs({
"CG_ASK_LOGIN",
"CG_ASK_CHANGE_SCENE",
"GC_ZZ_HUMAN_INFO",
"GC_ENTER_SCENE",
"CG_ENTER_SCENE_OK",
"CG_MOVE",
"GC_MOVE",
"CG_COPY_ENTER",
"CG_SKILL_FIRE",
"CG_CHAT",
"GC_HUMAN_DIE",
"CG_REVIVE_NOW",
}) do
	register_template(proto_id[v], set[v])
end
